<%@ include file="header.jsp" %>
<%@ page import="com.googlecode.jwsm.DatabaseLogHandler" %>
<%@ page import="java.util.*" %>
<%
	// Page Number
	int pageNumber = 1;
	if (request.getParameter("page") != null) {
		pageNumber = Integer.parseInt(request.getParameter("page"));
		session.setAttribute("page", String.valueOf(pageNumber));
	} else if (session.getAttribute("page") != null) {
		pageNumber = Integer.parseInt((String)session.getAttribute("page"));
	}
	
	if ("filters".equals(request.getParameter("type"))) {
		pageNumber = 1;
		session.setAttribute("page", String.valueOf(pageNumber));
	}

	// Sorting
	String sort = request.getParameter("sort");
	if (sort == null) {
		sort = (String)session.getAttribute("sort");
	} else {
		session.removeAttribute("reverse");
	}
	if (sort == null) {
		sort = "stamp";
	}
	session.setAttribute("sort", sort);
	boolean reverse = false;
	if (request.getParameter("reverse") != null) {
		if ("true".equals(request.getParameter("reverse"))) {
			reverse = true;
			session.setAttribute("reverse", "true");
		}
	} else if ("true".equals(session.getAttribute("reverse"))) {
		reverse = true;
	}
	
	String[] threadFilters;
	String[] levelFilters;
	String messageSearch;
	String[] serverFilters;
	Calendar startDate = null;
	Calendar endDate = null;
	if ("filters".equals(request.getParameter("type"))) {
		// Thread Filters
		threadFilters = request.getParameterValues("threadFilters");
		if (threadFilters == null) threadFilters = new String[0];
		session.setAttribute("threadFilters", threadFilters);
		
		// Level Filters
		levelFilters = request.getParameterValues("levelFilters");
		if (levelFilters == null) levelFilters = new String[0];
		session.setAttribute("levelFilters", levelFilters);
		
		// Message Search
		messageSearch = request.getParameter("messageSearch");
		if (messageSearch.trim().length() == 0) messageSearch = null;
		session.setAttribute("messageSearch", messageSearch);
		
		// Server Filters
		serverFilters = request.getParameterValues("serverFilters");
		if (serverFilters == null) serverFilters = new String[0];
		session.setAttribute("serverFilters", serverFilters);
		
		// Date Filter
		try {
			startDate = StringUtilities.convertToCalendar(request.getParameter("startDate"), "%M%/%d%/%yyyy% %HH%:%mm% %amPM%");
		} catch(Throwable t) {
			startDate = null;
		}
		session.setAttribute("startDate", startDate);
		try {
			endDate = StringUtilities.convertToCalendar(request.getParameter("endDate"), "%M%/%d%/%yyyy% %HH%:%mm% %amPM%");
		} catch(Throwable t) {
			endDate = null;
		}
		session.setAttribute("endDate", endDate);
	} else {
		threadFilters = (String[])session.getAttribute("threadFilters");
		levelFilters = (String[])session.getAttribute("levelFilters");
		messageSearch = (String)session.getAttribute("messageSearch");
		serverFilters = (String[])session.getAttribute("serverFilters");
		startDate = (Calendar)session.getAttribute("startDate");
		endDate = (Calendar)session.getAttribute("endDate");
	}
	
	int offset = (pageNumber - 1) * DatabaseLogHandler.MAX_RESULTS;
	
	QueryResult qr = DatabaseLogHandler.queryLogs(sort, reverse, offset, messageSearch, threadFilters, levelFilters, serverFilters, startDate, endDate);
	List<LogEntry> logs = qr.results;
	int totalLogs = qr.totalLogs;
	int displayed = 0;
	if ((logs != null) && (logs.size() > 0)) {
		displayed = logs.size() - 1 + offset;
	}
	
	int pages = (int)Math.ceil((float)totalLogs / (float)DatabaseLogHandler.MAX_RESULTS);
	if (pages == 0) pages = 1;
%>
<%@page import="org.jcommon.util.StringUtilities"%>
<span style="color: <%= CSSDefaults.BG_COLOR %>; font-size: 14pt; font-weight: bold;">Logs</span>
<br/><br/>
<form id="selectableForm" method="post">
<b>Date Range</b>: <input type="text" name="startDate" id="startDate" readonly="readonly"/><button type="reset" id="startDateSelect">...</button> - <input type="text" name="endDate" id="endDate" readonly="readonly"/><button type="reset" id="endDateSelect">...</button>&#160;<input type="submit" value="Filter"/>&#160;<input type="button" value="All" onclick="document.getElementById('startDate').value = ''; document.getElementById('endDate').value = ''; submit();"/>

<script type="text/javascript">
    Calendar.setup({
        inputField     :    "startDate",      // id of the input field
        ifFormat       :    "%m/%d/%Y %I:%M %p",       // format of the input field
        showsTime      :    true,            // will display a time selector
        button         :    "startDateSelect",   // trigger for the calendar (button ID)
        singleClick    :    true,           // double-click mode
        step           :    1                // show all years in drop-down boxes (instead of every other year as default)
    });
    
    Calendar.setup({
        inputField     :    "endDate",      // id of the input field
        ifFormat       :    "%m/%d/%Y %I:%M %p",       // format of the input field
        showsTime      :    true,            // will display a time selector
        button         :    "endDateSelect",   // trigger for the calendar (button ID)
        singleClick    :    true,           // double-click mode
        step           :    1                // show all years in drop-down boxes (instead of every other year as default)
    });
</script>
<br/><br/>
<%
	DatabaseLogHandler.updateSets();
	Set<String> threadList = DatabaseLogHandler.queryThreadFilters();
	Set<String> levelList = DatabaseLogHandler.queryLevelFilters();
	Set<String> serverList = DatabaseLogHandler.queryServerFilters();
%>
<table cellpadding="2" cellspacing="0" width="70%">
	<tr>
		<td width="40%">
			<% if (pageNumber > 1) { %>
				<a href="?page=<%= pageNumber - 1 %>">&lt;&lt; Previous</a>&#160;&#160;&#160;&#160;
			<% } else { %>
				&lt;&lt; Previous&#160;&#160;&#160;&#160;
			<% } %>
			<%
			{
				int i = 0;
				int directionalMax = 4;
				if (pageNumber - directionalMax - 1 > 0) i = pageNumber - directionalMax - 1;
				int maxPages = pages;
				if (pages > pageNumber + directionalMax) maxPages = pageNumber + directionalMax;
				for (; i < maxPages; i++) {
					if (i + 1 == pageNumber) {
			%>
					<b><%= i + 1 %></b>
			<%	
					} else {
			%>
					<a href="?page=<%= i + 1 %>"><%= i + 1 %></a>
			<%
					}
				}
			}
			%>
		</td>
		<td align="center" width="20%">Page <%= pageNumber %> of <%= pages %></td>
		<td align="right" width="40%">
			<% if (displayed > 0) { %>
			Displaying <%= 1 + offset %> - <%= displayed %> of <%= totalLogs %>
			<% } %>
			<% if (pageNumber < pages) { %>
				&#160;&#160;&#160;&#160;<a href="?page=<%= pageNumber + 1 %>">Next &gt;&gt;</a>
			<% } else { %>
				&#160;&#160;&#160;&#160;Next &gt;&gt;
			<% } %>
		</td>
	</tr>
	<tr><td colspan="3">
<table cellpadding="2" cellspacing="0" class="table" width="100%">
	<tr bgcolor="<%= CSSDefaults.BG_COLOR %>">
		<th class="table" id="threadHeader"><a href="?sort=threadName<% if (sort.equals("threadName")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Thread</b></a></th>
		<th class="table"><a href="?sort=className<% if (sort.equals("className")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Class</b></a></th>
		<th class="table"><a href="?sort=methodName<% if (sort.equals("methodName")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Method</b></a></th>
		<th class="table" id="levelHeader"><a href="?sort=level<% if (sort.equals("level")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Level</b></a></th>
		<th class="table" id="messageHeader"><a href="?sort=message<% if (sort.equals("message")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Message</b></a></th>
		<th class="table" id="serverHeader"><a href="?sort=server<% if (sort.equals("server")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Server</b></a></th>
		<th class="table" id="stampHeader"><a href="?sort=stamp<% if (sort.equals("stamp")) { %>&reverse=<%= !reverse %><% } %>" class="menu"><b>Time Stamp</b></a></th>
	</tr>
<%
	if (logs != null) {
		for (int i = 1; i < logs.size(); i++) {
			LogEntry entry = logs.get(i);
			String bgColor = "WHITE";
			if ("INIT".equals(entry.getLogLevelName())) {
				bgColor = "#95B8DB";
			} else if ("SEVERE".equals(entry.getLogLevelName())) {
				bgColor = "#EF7875";
			} else if (i % 2 == 0) {
				bgColor = "#EEEEEE";
			}
			String message = StringUtilities.breakLines(entry.getMessage(), 80);	// Problem here
			message = StringUtilities.text2HTML(message);
			%>
			<tr bgcolor="<%= bgColor %>" valign="top">
			<td class="log" nowrap="nowrap"><%= entry.getThreadName() %> (<%= entry.getThreadId() %>)</td>
			<td class="log" nowrap="nowrap"><%= entry.getClassName() %></td>
			<td class="log" nowrap="nowrap"><%= entry.getMethodName() %></td>
			<td class="log" nowrap="nowrap"><%= entry.getLogLevelName() %></td>
			<td class="log"<% if (("STACKTRACE".equals(entry.getLogLevelName())) || ("DEBUG".equals(entry.getLogLevelName()))) { %> style="font-size: x-small;"<% } %>><%= message %></td>
			<td class="log" nowrap="nowrap"><%= entry.getServer() %></td>
			<td class="log" nowrap="nowrap"><%= StringUtilities.format(entry.getTimestamp().getTimeInMillis(), "%MMMM% %d%, %yyyy% %hh%:%mm%:%ss%%amPM%") %></td>
			</tr>
			<%
		}
		if (logs.size() <= 1) {
%>
			<tr>
				<td class="table" colspan="7" align="center"><i>No log entries found</i></td>
			</tr>
<%
		}
	} else {
%>
	<tr>
		<td class="table" colspan="7" align="center"><i>Logging is disabled</i></td>
	</tr>
<%
	}
%>
</table>
</td></tr>
<tr>
		<td width="40%">
			<% if (pageNumber > 1) { %>
				<a href="?page=<%= pageNumber - 1 %>">&lt;&lt; Previous</a>&#160;&#160;&#160;&#160;
			<% } else { %>
				&lt;&lt; Previous&#160;&#160;&#160;&#160;
			<% } %>
			<%
			{
				int i = 0;
				int directionalMax = 4;
				if (pageNumber - directionalMax - 1 > 0) i = pageNumber - directionalMax - 1;
				int maxPages = pages;
				if (pages > pageNumber + directionalMax) maxPages = pageNumber + directionalMax;
				for (; i < maxPages; i++) {
					if (i + 1 == pageNumber) {
			%>
					<b><%= i + 1 %></b>
			<%	
					} else {
			%>
					<a href="?page=<%= i + 1 %>"><%= i + 1 %></a>
			<%
					}
				}
			}
			%>
		</td>
		<td align="center" width="20%">Page <%= pageNumber %> of <%= pages %></td>
		<td align="right" width="40%">
			<% if (displayed > 0) { %>
			Displaying <%= 1 + offset %> - <%= displayed %> of <%= totalLogs %>
			<% } %>
			<% if (pageNumber < pages) { %>
				&#160;&#160;&#160;&#160;<a href="?page=<%= pageNumber + 1 %>">Next &gt;&gt;</a>
			<% } else { %>
				&#160;&#160;&#160;&#160;Next &gt;&gt;
			<% } %>
		</td>
	</tr>
</table>
<input type="hidden" name="type" value="filters"/>
<div id="threadDiv" class="hidden" align="left">
<% for (String t : threadList) { %>
	<%
		boolean checked = false;
		if (threadFilters != null) {
			for (int j = 0; j < threadFilters.length; j++) {
				if (threadFilters[j].equals(t)) {
					checked = true;
					break;
				}
			}
		}
		if ((threadFilters == null) || (threadFilters.length == 0)) checked = true;
	%>
	<input name="threadFilters" value="<%= t %>" onchange="submit();" type="checkbox"<% if (checked) { %> checked="checked"<% } %>> <span onclick="selectAndSubmit('threadFilters', '<%= t %>');"><%= t %></span><br/>
<% } %>
	<input type="button" value="Select All" style="margin-top: 5px;" onclick="selectAndSubmit('threadFilters');"/>
</div>
<div id="levelDiv" class="hidden" align="left">
<% for (String level : levelList) { %>
	<%
		boolean checked = false;
		if (levelFilters != null) {
			for (int j = 0; j < levelFilters.length; j++) {
				if (levelFilters[j].equals(level)) {
					checked = true;
					break;
				}
			}
		}
		if ((levelFilters == null) || (levelFilters.length == 0)) checked = true;
	%>
	<input name="levelFilters" value="<%= level %>" onchange="submit();" type="checkbox"<% if (checked) { %> checked="checked"<% } %>> <span onclick="selectAndSubmit('levelFilters', '<%= level %>');"><%= level %></span><br/>
<% } %>
	<input type="button" value="Select All" style="margin-top: 5px;" onclick="selectAndSubmit('levelFilters');"/>
</div>
<div id="serverDiv" class="hidden" align="left">
<% for (String server : serverList) { %>
	<%
		boolean checked = false;
		if (serverFilters != null) {
			for (int j = 0; j < serverFilters.length; j++) {
				if (serverFilters[j].equals(server)) {
					checked = true;
					break;
				}
			}
		}
		if ((serverFilters == null) || (serverFilters.length == 0)) checked = true;
	%>
	<nobr><input name="serverFilters" value="<%= server %>" onchange="submit();" type="checkbox"<% if (checked) { %> checked="checked"<% } %>> <span onclick="selectAndSubmit('serverFilters', '<%= server %>');"><%= server %></span></nobr><br/>
<% } %>
	<input type="button" value="Select All" style="margin-top: 5px;" onclick="selectAndSubmit('serverFilters');"/>
</div>
<div id="messageDiv" class="hidden" align="left">
	<b>Search:</b> <input type="text" id="messageSearchField" name="messageSearch"<% if (messageSearch != null) { %> value="<%= messageSearch %>"<% } %> size="25"/> <input type="button" value="Clear" onclick="document.getElementById('messageSearchField').value = ''; submit();"/>
</div>
</form>
<script language="JavaScript">
	attachPopup(null, 'threadHeader', 'threadDiv', 'hover', 'y');
	attachPopup(null, 'levelHeader', 'levelDiv', 'hover', 'y');
	attachPopup(null, 'messageHeader', 'messageDiv', 'hover', 'y');
	//attachPopup(null, 'stampHeader', 'stampDiv', 'hover', 'y');
	attachPopup(null, 'serverHeader', 'serverDiv', 'hover', 'y');
<% if (startDate != null) { %>
	document.getElementById('startDate').value = '<%= StringUtilities.format(startDate, "%M%/%d%/%yyyy% %HH%:%mm% %amPM%") %>';
<% } %>
<% if (endDate != null) { %>
	document.getElementById('endDate').value = '<%= StringUtilities.format(endDate, "%M%/%d%/%yyyy% %HH%:%mm% %amPM%") %>';
<% } %>

	function selectAndSubmit(checkName, checkValue) {
		var checkboxGroup = document.getElementsByName(checkName);
		for (var i = 0; i < checkboxGroup.length; i++) {
			if (checkboxGroup[i].value == checkValue) {
				checkboxGroup[i].checked = true;
			} else {
				checkboxGroup[i].checked = false;
			}
		}
		document.getElementById('selectableForm').submit();
	}
</script>
<%@ include file="footer.jsp" %>